package task

import (
	"github.com/gocraft/web"
	"fmt"
	"io/ioutil"
	"encoding/json"
	"path/filepath"
)

import (
	"../config"
	"../response"
	"os"
)

func (*Task) CreateTask(rw web.ResponseWriter, req *web.Request) {
	//fmt.Fprintln(rw, "CreateTask response.")
	var resp = TaskCreateResponse{response.Response{Code: 1, Message: "createtask failed."}, TaskStatus{}}

	body, err := ioutil.ReadAll(req.Body)
	if err != nil {
		resp.Message = err.Error()
		responseBody, _ := json.Marshal(resp)
		rw.Write(responseBody)
		return
	}

	var t Task
	err = json.Unmarshal(body, &t)
	if err != nil {
		resp.Message = err.Error()
		responseBody, _ := json.Marshal(resp)
		rw.Write(responseBody)
		return
	}

	err = t.Validate()
	if err != nil {
		resp.Message = err.Error()
		responseBody, _ := json.Marshal(resp)
		rw.Write(responseBody)
		return
	}

	fmt.Println("parse task successfully")
	resp.TaskStatus, err = TaskSheetCreate(string(body))
	if err != nil {
		fmt.Fprintln(rw, err.Error())
	}
	resp.Code = 0
	resp.Message = "createtask success."
	responseBody, _ := json.Marshal(resp)
	rw.WriteHeader(201)
	rw.Write(responseBody)
	return
}

//获取所有
func (*Task) AllTasks(rw web.ResponseWriter, req *web.Request) {
	var tasks []TaskStatus
	var resp allTasksResponse

	jobstore, _ := ioutil.ReadDir(config.Conf.WorkSpacePath)

	for _, path := range jobstore {
		if path.IsDir() {
			taskstatuspath := filepath.Join(config.Conf.WorkSpacePath, path.Name()) + "/status.json"
			//taskconfig := filepath.Join(config.Conf.WorkSpacePath, path.Name())+"/config.json"

			var taskstatus TaskStatus
			body, _ := ioutil.ReadFile(taskstatuspath)
			json.Unmarshal(body, &taskstatus)
			tasks = append(tasks, taskstatus)
		}

	}
	resp.Code = 0
	resp.Message = "get all tasks success."
	resp.Tasks = tasks

	respBody, _ := json.Marshal(resp)
	rw.Write(respBody)
}

func (t *Task)GetTask(rw web.ResponseWriter, req *web.Request)  {
	resp := getTaskResponse{response.Response{Code:1,Message:"task not exist."},TaskStatus{}}
	taskname := req.PathParams["name"]
	taskstatuspath := filepath.Join(config.Conf.WorkSpacePath, taskname) + "/status.json"
	if _,err := os.Stat(taskstatuspath); err==nil{
		body,_:= ioutil.ReadFile(taskstatuspath)
		json.Unmarshal(body,&resp.TaskStatus)
		resp.Code = 0
		resp.Message = "get task success."
	}
	respBody,_ :=json.Marshal(resp)
	rw.WriteHeader(200)
	rw.Write(respBody)
}



//检查task body
func (t Task) Validate() error {

	err := t.Input.IsValid()
	if err != nil {
		return err
	}

	err = t.Filter.IsValid()
	if err != nil {
		return err
	}

	err = t.Output.IsValid()
	if err != nil {
		return err
	}
	return nil
}
